package com.portal.service.impl;

import com.portal.enums.RegisterResult;
import com.portal.model.dto.UserRegisterParam;
import com.portal.service.UserService;
import com.test.mapper.UserMapper;
import com.test.model.User;
import com.test.model.UserExample;
import com.test.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Override
    public User getUserByUsername(String userName) {
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(userName);
        List<User> users = userMapper.selectByExample(example);

//        if(users != null && users.size()>0){}
        if(!CollectionUtils.isEmpty(users)){
            return users.get(0);
        }

        return null;
    }

    @Override
    public RegisterResult register(UserRegisterParam userRegisterParam) {

        System.out.println(userRegisterParam);
        //如果账号或密码为空
        if(userRegisterParam.getUserName() == null || userRegisterParam.getPassword() == null){
            return RegisterResult.NAME_PASSWORD_NULL;
        }
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(userRegisterParam.getUserName());
        //如果用户名存在
        if(userMapper.countByExample(userExample)>0){
            return RegisterResult.USERNAME_EXIST;
        }
        //如果账号密码过长（大于十）
        if(userRegisterParam.getUserName().length()>=10 || userRegisterParam.getPassword().length()>=10)
        {
            return RegisterResult.NAME_PASSWORD_TOO_LONG;

        }
        User user = new User();

        user.setUsername(userRegisterParam.getUserName());
        user.setPassword(passwordEncoder.encode(userRegisterParam.getPassword()));

        user.setPhone(userRegisterParam.getPhone());

        if(userMapper.insertSelective(user)>0)
        {
            return RegisterResult.REG_SUCCESS;
        }
        return RegisterResult.REG_FAILED;
    }

    @Override
    public Map<String, String> login(String userName, String password) {

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, password);
        Authentication authentication = null;
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(userName);
        List<User> users = userMapper.selectByExample(userExample);

        System.out.println(users);
        if(users.size()==0){
            Map<String,String> map = new HashMap<>();
            return map;
        }
        //验证token
        try{
            authentication = authenticationManager.authenticate(token);
        }catch (AuthenticationException e){
            System.out.println("密码错误");
        }

        SecurityContextHolder.getContext().setAuthentication(authentication);
        Map<String,String> tokenMap = new HashMap<>();
        System.out.println(authentication);
        if(authentication != null){
            //通过验证返回的authenticate中获取userDetails
            UserDetails userDetails =(UserDetails) authentication.getPrincipal();
            //根据userDetails生成token字符串
            String tokenString = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token",tokenString);
            tokenMap.put("tokenHead",jwtTokenUtil.getTokenHead());
            tokenMap.put("tokenHeader",jwtTokenUtil.getTokenHeader());

        }
        return tokenMap;
    }
}
